import React, {useEffect, useState} from 'react';
import {connect} from 'react-redux';
import {Table, Button, Modal, Form, Input, InputNumber, message, Tooltip} from 'antd';
import {defaultPagination, TableBtn} from "../publicComponents";
import {get, post} from "../../../utils";
import {mUrl} from "../../../config";
import moment from "moment";
import { PlusOutlined, ReloadOutlined } from '@ant-design/icons';

const Page = () => {
    const [form] = Form.useForm();
    const columns = [
        {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            align: 'center',
            width: 90,
            render: (text, record, index) => index + 1
        },
        {
            title: '操作',
            align: 'center',
            width: 150,
            render: (text, record, index) => {
                return (
                    <TableBtn
                        onClick={handleTableBtnClick}
                        record={record}
                        btns={[
                            {id: 1, name: '修改'},
                            // {id: 2, name: '停用'},
                            {id: 3, name: '删除'}
                        ]}
                    />
                );
            }
        },
        // {
        //     title: '状态',
        //     dataIndex: 'state',
        //     key: 'state',
        //     align: 'center',
        // },
        {
            title: '置顶周期/天',
            dataIndex: 'longtimes',
            align: 'center',
        },
        {
            title: '付费金额/元',
            dataIndex: 'cost',
            align: 'center',
        },
        {
            title: '备注',
            dataIndex: 'remark',
            align: 'center',
            render: remark => {
                let text = remark || '--';
                return (
                    <Tooltip placement={'topLeft'} title={remark}>
                        {text.length > 15 ? text.substr(0, 15) + '...' : text}
                    </Tooltip>
                );
            }
        },
        {
            title: '创建人',
            dataIndex: 'createuser',
            align: 'center',
        },
        {
            title: '创建时间',
            dataIndex: 'createtime',
            align: 'center',
            render: time => moment(time).format('YYYY-MM-DD')
        },
    ];

    const [tableData, setTableData] = useState([]); // 表格数据
    const [visible, setVisible] = useState(false);
    const [detail, setDetail] = useState({});
    const [pagination, setPagination] = useState(Object.assign({}, defaultPagination)); // 页码
    useEffect(() => {
        fetch();
    }, []);

    const fetch = (params = {}) => {
        let start = 1;
        if (params.startList > 1) {
            start = params.startList;
        }
        get(mUrl.searchAgreemenstingList, {
            agreementtype: 3,
            pageNo: start, pageSize: pagination.pageSize, ...params
        }).then((res) => {
            const {list = [], count = 0} = res.data;
            pagination.total = count;
            setPagination(pagination);
            setTableData(list);
        });
    };

    const handleTableBtnClick = (id, record) => {
        if (id === 1) { // 点击修改
            setDetail(record);
            setTimeout(() => {
                setVisible(true);
            }, 500);
        } else if (id === 3) { // 点击删除
            Modal.confirm({
                title: '提示',
                content: '是否确定将该消息删除？',
                onOk: async () => {
                    const {state} = await get(mUrl.deAgreemensting, {greemensting: record.agreemensting});
                    if (state === 1) {
                        message.success("成功");
                        fetch();
                    }
                }
            });
        }
    };
    
    const handleTableChange = (page) => {
        pagination.current = page.current;
        pagination.pageSize = page.pageSize;
        setPagination(pagination);
        fetch({
            startList: pagination.current
        });
    };
    
    return (
        <div style={{padding: 14, background: '#fff', minHeight: 360}}>
            <label><p>消费付费设置 / 消费置顶付费设置</p></label>
            <div style={{marginBottom: 10}}>
                <Button
                    type='primary'
                    onClick={() => {
                        setVisible(true);
                    }}
                >
                    <PlusOutlined/>新增
                </Button>
                <Button
                    type='primary'
                    style={{marginLeft: 5}}
                    onClick={() => fetch()}
                >
                    <ReloadOutlined/>刷新
                </Button>
            </div>
            <Table
                rowKey={(data) => {
                    return data.agreemensting;
                }}
                dataSource={tableData}
                columns={columns}
                size='small'
                bordered
                pagination={pagination}
                onChange={handleTableChange}
            />
            <EditModal
                form={form}
                visible={visible}
                detail={detail}
                setVisible={setVisible}
                onSubmit={() => {
                    fetch();
                    setVisible(false);
                }}
            />
        </div>
    );
};

const EditModal = (props) => {
    const {visible = false, setVisible, form, detail = {}, onSubmit} = props;

    useEffect(() => {
        if (!visible) {
            form.resetFields();
        } else {
            if (detail.agreemensting) {
                form.setFieldsValue({
                    longtimes: detail.longtimes,
                    cost: detail.cost,
                    remark: detail.remark
                });
            }
        }
    }, [visible]);

    const onFinish = async (values) => {
        let url = mUrl.addAgreemensting;
        if (detail.agreemensting) {
            url = mUrl.upAgreemensting;
            values.agreemensting = detail.agreemensting;
        }
        values.agreementtype = 3;
        const res = await post(url, values);
        if (res.state === 1) {
            message.success('设置成功');
            onSubmit();
        }
    };
    return (
        <Modal
            title={detail.agreemensting ? '修改付费项' : '新增付费项'}
            visible={visible}
            onCancel={_ => setVisible(false)}
            footer={null}
            getContainer={false}
        >
            <Form form={form} onFinish={onFinish}>
                <Form.Item
                    label='置顶周期项'
                    name='longtimes'
                    rules={[{required: true, message: '请输入置顶周期'}]}
                    labelCol={{span: 6}}
                >
                    <InputNumber min={1} placeholder={'请输入'}/>
                </Form.Item>
                <Form.Item
                    label='付费金额'
                    name='cost'
                    rules={[{required: true, message: '请输入付费金额'}]}
                    labelCol={{span: 6}}
                >
                    <InputNumber/>
                </Form.Item>
                <Form.Item
                    label='备注'
                    name='remark'
                    labelCol={{span: 6}}
                >
                    <Input/>
                </Form.Item>
                <Form.Item style={{marginTop: 10, textAlign: 'center'}}>
                    <Button
                        htmlType="submit" type={'primary'}
                    >提交</Button>
                    <Button style={{marginLeft: 15}}
                            onClick={_ => setVisible(false)}
                    >取消</Button>
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default connect()(Page);